package com.example.membersteward.service.impl;

import com.example.membersteward.common.CommonResult;
import com.example.membersteward.entity.ExcelTableInfo;
import com.example.membersteward.entity.User;
import com.example.membersteward.entity.vo.UserVo;
import com.example.membersteward.enums.Sex;
import com.example.membersteward.enums.UserStatus;
import com.example.membersteward.mapper.UserMapper;
import com.example.membersteward.service.FileService;
import com.example.membersteward.util.BaseUtils;
import com.example.membersteward.util.ExcelUtils;
import com.example.membersteward.util.SecurityUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;


@Service
public class FileServiceImpl implements FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0");

    @Resource
    UserMapper userMapper;
    @Value("${user.username.regex}")
    private String usernameRegex;
    @Value("${resource.virtualPath}")
    private String virtualPath;
    @Value("${resource.defaultImg}")
    private String defaultImg;

    @Override
    public CommonResult downloadTemp() {
        try {
            List<ExcelTableInfo> userTable = ExcelTableInfo.getUserTableExcelTemp();
            return ExcelUtils.generateExcelTemplate(userTable, null);
        } catch (Exception e) {
            logger.error("执行异常！", e);
            return CommonResult.error("执行异常");
        }
    }

    @Override
    public CommonResult exportUserInfo(UserVo userVo) {
        try {
            List<ExcelTableInfo> userTable = ExcelTableInfo.exportUserTable();
            userVo.setStartDate(BaseUtils.getMinDate(userVo.getStartDate()));
            userVo.setEndDate(BaseUtils.getMaxDate(userVo.getEndDate()));
            List<User> info = userMapper.getExportUserInfo(userVo);
            if (BaseUtils.isEmpty(info)) {
                return CommonResult.error("没有可以导出的记录");
            }
            String[][] result = new String[info.size()][10];
            for (int i = 0; i < info.size(); i++) {
                User user = info.get(i);
                result[i][0] = user.getUsername();
                result[i][1] = user.getUserAcct();
                result[i][2] = user.getPhone();
                result[i][3] = Sex.getMsgByCode(user.getSex());
                result[i][4] = UserStatus.getMsgByCode(user.getStatus());
                result[i][5] = user.getEmail();
                result[i][6] = BaseUtils.Date2String(user.getBirthday(), BaseUtils.DATE_FORMAT_2);
                result[i][7] = user.getAddress();
                result[i][8] = user.getPersonProfile();
                result[i][9] = BaseUtils.Date2String(user.getLastUpdateTime(), BaseUtils.DATE_FORMAT_4);
            }
            return ExcelUtils.generateExcelTemplate(userTable, result);
        } catch (Exception e) {
            logger.error("执行异常！", e);
            return CommonResult.error("执行异常");
        }
    }

    @Override
    public CommonResult uploadUserInfo(MultipartFile file) {
        int fail = 0;
        int success = 0;
        int total = 0;
        InputStream inputStream = null;
        Workbook workbook = null;
        try {
            inputStream = file.getInputStream();
            workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            total = sheet.getLastRowNum();
            long a = System.currentTimeMillis();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                String username = getCellValueAsString(row.getCell(0));
                String userAcct = getCellValueAsString(row.getCell(1));
                String phone = getCellValueAsString(row.getCell(2));
                String sex = getCellValueAsString(row.getCell(3));
                String email = getCellValueAsString(row.getCell(4));
                String birthday = getCellValueAsString(row.getCell(5));
                String address = getCellValueAsString(row.getCell(6));
                if (BaseUtils.isEmpty(username) || username.length() > 10 ||
                        BaseUtils.isEmpty(userAcct) || !Pattern.compile(usernameRegex).matcher(userAcct).matches() ||
                        BaseUtils.isEmpty(phone) || BaseUtils.isEmpty(sex)) {
                    fail++;
                }
                User user = new User();
                user.setUsername(username);
                user.setUserAcct(userAcct);
                user.setPhone(phone);
                user.setSex(Sex.getCodeByMsg(sex));
                user.setEmail(email);
                user.setBirthday(BaseUtils.String2Date(birthday, BaseUtils.DATE_FORMAT_2));
                user.setAddress(address);
                user.setCreateTime(new Date());
                user.setLastUpdateTime(new Date());
                // 状态默认给 1-正常
                user.setStatus(UserStatus.NORMAL.getCode());
                // 默认密码
                user.setPassword(SecurityUtils.DEFAULT_PASSWORD);
                // 默认头像
                user.setImgPath(virtualPath + defaultImg);
                try {
                    int ret = userMapper.insert(user);
                    if (ret > 0) {
                        success++;
                    } else {
                        fail++;
                    }
                } catch (Exception e) {
                    fail++;
                    logger.error("新增失败");
                }
            }
            return CommonResult.success("文件总内容：" + total + ", 成功笔数：" + success + "，失败笔数：" + fail);
        } catch (IOException e) {
            logger.error("执行异常", e);
            return CommonResult.error("文件读取或解析失败，请检查文件格式或内容。");
        } catch (Exception e) {
            logger.error("执行异常", e);
            return CommonResult.error("发生未知错误，请联系管理员。");
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error("执行异常", e);
            }
        }
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    return BaseUtils.Date2String(date, BaseUtils.DATE_FORMAT_2);
                } else {
                    return DECIMAL_FORMAT.format(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}
